package com.zch.client.spring.mqtt.client;

import com.zch.client.spring.mqtt.callback.MqttClientRootCallback;
import com.zch.client.spring.mqtt.dto.MqttSendRequest;
import com.zch.client.spring.mqtt.dto.MqttSubscribeRequest;
import com.zch.client.spring.mqtt.properties.MqttAutoConfigProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
@Slf4j
public class FastMqttClient {
     MqttClient client;
     MqttAutoConfigProperties mqttAutoConfigProperties;

     @Autowired
     MqttClientRootCallback mqttClientRootCallback;


    /**
     * 在bean初始化后 自动注册到MQTT 服务端跟 服务器保持长连接
     */
    @PostConstruct
    public void init() {
        connect();
    }
    /**
     * 客户端连接服务端
     */
    public void connect() {
        try{
            String subscribeTopics = mqttAutoConfigProperties.getSubscribeTopics();
            String subscribeQos = mqttAutoConfigProperties.getSubscribeQos();
            //创建MQTT客户端对象
            client = new MqttClient(mqttAutoConfigProperties.getUrl(),mqttAutoConfigProperties.getClientId(),
                    new MemoryPersistence());
            //连接设置
            MqttConnectOptions options = new MqttConnectOptions();
            //是否清空session，设置false表示服务器会保留客户端的连接记录（订阅主题，qos）,客户端重连之后能获取到服务器在客户端断开连接期间推送的消息
            //设置为true表示每次连接服务器都是以新的身份
            options.setCleanSession(true);
            //设置连接用户名
            options.setUserName(mqttAutoConfigProperties.getUsername());
            //设置连接密码
            options.setPassword(mqttAutoConfigProperties.getPassword().toCharArray());
            //设置超时时间，单位为秒
            options.setConnectionTimeout(mqttAutoConfigProperties.getConnectTimeoutSeconds());
            //设置心跳时间 单位为秒，如果20 则表示服务器每隔 1.5*20秒的时间向客户端发送心跳判断客户端是否在线
            options.setKeepAliveInterval(mqttAutoConfigProperties.getKeepAliveSeconds());
            //设置遗嘱消息的话题，若客户端和服务器之间的连接意外断开，服务器将发布客户端的遗嘱信息
            options.setWill(mqttAutoConfigProperties.getWillTopic(),
                    (mqttAutoConfigProperties.getClientId() + "与服务器断开连接").getBytes(),0,false);
            //设置一个客户端的最根的回调
            client.setCallback(mqttClientRootCallback);
            client.connect(options);
            //订阅主题
            //消息等级，和主题数组一一对应，服务端将按照指定等级给订阅了主题的客户端推送消息
            //int[] qos = subscribeQos.
            //主题
            String[] topics =null;
            if(StringUtils.isNotBlank(subscribeTopics)){
                topics = subscribeTopics.split(",");
            }
            if(topics != null && topics.length > 0){
                //这里如果有多个topic 订阅 都会统一走到根回调mqttClientRootCallback,业务可以根据根回调里再细分topic 的处理逻辑
                client.subscribe(topics);
            }
        } catch(MqttException e){
            e.printStackTrace();
        }

    }

    //发送者发送消息
    public void send(MqttSendRequest mqttRequest){
        if(mqttRequest == null|| StringUtils.isEmpty(mqttRequest.getMessage())||StringUtils.isEmpty(mqttRequest.getTopic())){
            return;
        }
        MqttMessage mqttMessage = new MqttMessage();
        mqttMessage.setQos(mqttRequest.getQos());
        mqttMessage.setRetained(mqttRequest.isRetained());
        mqttMessage.setPayload(mqttRequest.getMessage().getBytes());
        //主题的目的地，用于发布/订阅信息
        MqttTopic mqttTopic = client.getTopic(mqttRequest.getTopic());
        //提供一种机制来跟踪消息的传递进度
        //用于在以非阻塞方式（在后台运行）执行发布是跟踪消息的传递进度
        MqttDeliveryToken token;
        try {
            //将指定消息发布到主题，但不等待消息传递完成，返回的token可用于跟踪消息的传递状态
            //一旦此方法干净地返回，消息就已被客户端接受发布，当连接可用，将在后台完成消息传递。
            token = mqttTopic.publish(mqttMessage);
            token.waitForCompletion();
        } catch (MqttException e) {
            log.error("send error ", e);

        }
    }
    /**
     * 消费者主动订阅某  单个主题
     */
    public void subscribe(MqttSubscribeRequest subscribeRequest) {
        try {
            if(subscribeRequest != null){
                client.subscribe(subscribeRequest.getTopic(), subscribeRequest.getQos(),subscribeRequest.getMessageListener());
            }else{
                client.subscribe(subscribeRequest.getTopic(),subscribeRequest.getQos());
            }
        } catch (MqttException e) {
            log.error("subscribe error ", e);
        }
    }

    /**
     * 断开连接
     */
    public void disConnect() {
        try {
            client.disconnect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    public void setMqttAutoConfigProperties(MqttAutoConfigProperties mqttAutoConfigProperties) {
        this.mqttAutoConfigProperties = mqttAutoConfigProperties;
    }
}
